package com.shopmall.controller.goods;


import com.shopmall.common.ResponseData;
import com.shopmall.goods.entity.Material;
import com.shopmall.goods.service.IMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

@RestController
@RequestMapping("/material")
public class MaterialController extends ResponseData {

    @Autowired
    private IMaterialService materialService;

    @PostMapping("/upload")
    public ResponseData uploadFile(@RequestParam("file")MultipartFile file,@RequestParam("classify")String classift){
        String targetPath = "D:/data/"+file.getOriginalFilename();
        try(InputStream inputStream = file.getInputStream();
            OutputStream outputStream = new FileOutputStream(targetPath))
        {
            File target = new File(targetPath);
            if(!target.exists()){
                target.createNewFile();
            }
            byte[] buffer = new byte[1024];
            int bytesRead = -1;
            while((bytesRead=inputStream.read(buffer))!=-1){
                outputStream.write(buffer,0,bytesRead);
            }
            if(classift!=null && !"".equals(classift)){
                Material material = new Material();
                material.setFileName(file.getOriginalFilename());
                material.setFilePath(targetPath);
                material.setClassify(classift);
                materialService.addMaterial(material);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return success(file.getOriginalFilename());
    }

    /**
     * 分页显示图片
     * @param material
     * @return
     */
    @PostMapping("materialPageList")
    public ResponseData materialPageList(@RequestBody Material material){
        return success(materialService.materialPageList(material));
    }

    /**
     * 移动图片到指定的分类
     * @param list
     * @return
     */
    @PostMapping("updateClassify")
    public ResponseData updateClassify(@RequestBody List<Material> list){
        int i = materialService.updateMaterialClassify(list);
        if(i>0){
            return  success("成功");
        }
        return failed("失败");
    }

}
